package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.bo.YunZhanTingEnterpriseHistoryRequest;
import com.aiti.lulian.dto.EnterpriseSelectDto;
import com.aiti.lulian.dto.SearchDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.request.LuLianEnterpriseRenZhengRequest;
import com.aiti.lulian.entity.vr.EnterpriseVr;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.feign.ScaleEnterpriseService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.service.ILuLianEnterpriseMainIndustrySerivce;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILulianEnterpriseHistoryService;
import com.aiti.lulian.utils.NotificationUtils;
import com.aiti.lulian.vo.EnterpriseAuthVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LulianEnterpriseHistoryServiceImpl extends BaseSerivceImpl<LuLianEnterpriseHistoryMapper, LuLianEnterpriseHistory> implements ILulianEnterpriseHistoryService {

    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;

    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;

    private LuLianEnterpriseHistoryCiMapper luLianEnterpriseHistoryCiMapper;

    private LuLianEnterpriseProveMapper luLianEnterpriseProveMapper;

    private ILuLianEnterpriseMainIndustrySerivce luLianEnterpriseMainIndustrySerivce;

    private ILuLianEnterpriseService luLianEnterpriseService;

    private LuLianShowEnterpriseAuthMapper luLianShowEnterpriseAuthMapper;

    private NotificationUtils notificationUtils;

    private ScaleEnterpriseService scaleEnterpriseService;

    private SysAreaMapper sysAreaMapper;

    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private EnterpriseVrMapper enterpriseVrMapper;

    private CloudShowManagerSubService cloudShowManagerSubService;
    public LulianEnterpriseHistoryServiceImpl(LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper,
                                              LuLianEnterpriseUserMapper luLianEnterpriseUserMapper,
                                              LuLianEnterpriseHistoryCiMapper luLianEnterpriseHistoryCiMapper,
                                              LuLianEnterpriseProveMapper luLianEnterpriseProveMapper,
                                              ILuLianEnterpriseMainIndustrySerivce luLianEnterpriseMainIndustrySerivce,
                                              LuLianShowEnterpriseAuthMapper luLianShowEnterpriseAuthMapper,
                                              ILuLianEnterpriseService luLianEnterpriseService,
                                              NotificationUtils notificationUtils,
                                              ScaleEnterpriseService scaleEnterpriseService,
                                              SysAreaMapper sysAreaMapper,
                                              SysDictDataMapper sysDictDataMapper,
                                              CloudShowManagerSubService cloudShowManagerSubService) {
        this.luLianEnterpriseHistoryMapper = luLianEnterpriseHistoryMapper;
        this.luLianEnterpriseUserMapper = luLianEnterpriseUserMapper;
        this.luLianEnterpriseHistoryCiMapper =luLianEnterpriseHistoryCiMapper;
        this.luLianEnterpriseProveMapper = luLianEnterpriseProveMapper;
        this.luLianEnterpriseMainIndustrySerivce = luLianEnterpriseMainIndustrySerivce;
        this.luLianShowEnterpriseAuthMapper = luLianShowEnterpriseAuthMapper;
        this.cloudShowManagerSubService = cloudShowManagerSubService;
        this.luLianEnterpriseService = luLianEnterpriseService;
        this.notificationUtils = notificationUtils;
        this.scaleEnterpriseService = scaleEnterpriseService;
        this.sysAreaMapper = sysAreaMapper;
        this.sysDictDataMapper = sysDictDataMapper;
    }

    /**
     * 企业认证
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message addEnterpriseHistory(LuLianEnterpriseRenZhengRequest request,String userId) {

        if(StringUtils.isBlank(request.getBaseId())){
            //社会统一信用代码
            String unicode = request.getUnicode();
            Integer enterpriseCount = luLianEnterpriseHistoryMapper.selectCount(new QueryWrapper<LuLianEnterpriseHistory>().eq("unicode", unicode));
            if(enterpriseCount > 0){
                log.error("当前企业已存在%s",unicode);
                return Message.fail(String.format("当前信用代码【%s】已存在",unicode));
            }else{
                String enterpriseId = IdUtil.simpleUUID();

                //判断userId对应的用户是否绑定过企业，如果已绑定直接提示
                Integer userBindEnterpriseCount = luLianEnterpriseUserMapper.selectCount(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
                if(userBindEnterpriseCount == null){
                    userBindEnterpriseCount = Integer.parseInt("0");
                }
                if(userBindEnterpriseCount > 0 ){
                    return Message.fail("该手机号已绑定了企业，请更换");
                }

                LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder()
                        .enterpriseId(enterpriseId)
                        .userId(userId)
                        .baseId(IdUtil.simpleUUID())
                        .build();
                luLianEnterpriseUserMapper.insert(enterpriseUser);
                //构建History数据
                LuLianEnterpriseHistory enterpriseHistory = new LuLianEnterpriseHistory();
                BeanUtils.copyProperties(request,enterpriseHistory);
                enterpriseHistory.setBaseId(enterpriseId);
                enterpriseHistory.setRegisterCapital(request.getRegisterCapital());
                enterpriseHistory.setIsAuth(false);
                enterpriseHistory.setExamineStatus("");
                enterpriseHistory.setStatus("1");
                enterpriseHistory.setCreator(userId);
                enterpriseHistory.setContactAddress("");
                enterpriseHistory.setBaseCreateTime(DateUtil.formatDateTime(new Date()));
                luLianEnterpriseHistoryMapper.insert(enterpriseHistory);

                //构建复加表数据
                if(StringUtils.isBlank(request.getFlag())){
                    LuLianEnterpriseHistoryCi luLianEnterpriseHistoryCi = new LuLianEnterpriseHistoryCi();
                    BeanUtils.copyProperties(request,luLianEnterpriseHistoryCi);
                    luLianEnterpriseHistoryCi.setBaseId(IdUtil.simpleUUID());
                    luLianEnterpriseHistoryCi.setPkId(enterpriseId);
                    luLianEnterpriseHistoryCiMapper.saveHistoryCiData(luLianEnterpriseHistoryCi);
                }
                //插入营业执照数据
                LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseId);
                if(luLianEnterpriseProve != null){
                    luLianEnterpriseProve.setBusinessLicenseUrl(request.getBusinessLicenseUrl());
                    luLianEnterpriseProveMapper.updateById(luLianEnterpriseProve);
                }else{
                    if(StringUtils.isNotBlank(request.getBusinessLicenseUrl())){
                        luLianEnterpriseProve = LuLianEnterpriseProve.builder()
                                .baseId(IdUtil.simpleUUID())
                                .enterpriseId(enterpriseId)
                                .businessLicenseUrl(request.getBusinessLicenseUrl())
                                .build();
                        luLianEnterpriseProveMapper.insert(luLianEnterpriseProve);
                    }
                }

                //构建行业门类
                List<LuLianEnterpriseMainIndustry> mainIndustrys = request.getMainIndustrys();
                if(mainIndustrys != null && !mainIndustrys.isEmpty()){
                    List<LuLianEnterpriseMainIndustry> collect = mainIndustrys.stream().map(item -> {
                        item.setEnterpriseId(enterpriseId);
                        return item;
                    }).collect(Collectors.toList());
                    luLianEnterpriseMainIndustrySerivce.saveOrUpdateBatch(collect);
                }
            }
        }else{
            return Message.fail("插入操作,不能携带BaseId数据");
        }

        return Message.success("保存成功");
    }

    /**
     * 更新企业认证
     *
     * @param request
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message updateEnterpriseHistory(LuLianEnterpriseRenZhengRequest request, String userId) {
        if(StringUtils.isBlank(request.getBaseId())){
            return Message.fail("没有找到BaseId");
        }

        //查询当前统信是否已存在
        Integer unicodeCount = luLianEnterpriseHistoryMapper.selectCount(new QueryWrapper<LuLianEnterpriseHistory>().eq("unicode", request.getUnicode()).ne("base_id", request.getBaseId()));
        if(unicodeCount > 0 ){
            return Message.fail(String.format("当前信用代码【%s】已经存在！",request.getUnicode()));
        }

        LuLianEnterpriseHistory enterpriseHistory = luLianEnterpriseHistoryMapper.selectById(request.getBaseId());
        BeanUtils.copyProperties(request,enterpriseHistory);
        enterpriseHistory.setExamineStatus("");
        enterpriseHistory.setStatus("0");
        enterpriseHistory.setBaseUpdateTime(DateUtil.formatDateTime(new Date()));


        UpdateWrapper<LuLianEnterpriseHistory> updateWrapper = new UpdateWrapper<LuLianEnterpriseHistory>()
                .set("base_name", enterpriseHistory.getBaseName())
                .set("unicode", enterpriseHistory.getUnicode())
                .set("legal_person", enterpriseHistory.getLegalPerson())
                .set("register_type", enterpriseHistory.getRegisterType())
                .set("register_capital", enterpriseHistory.getRegisterCapital())
                .set("enterprise_term_type", enterpriseHistory.getEnterpriseTermType())
                .set("province", enterpriseHistory.getProvince())
                .set("city", enterpriseHistory.getCity())
                .set("county", enterpriseHistory.getCounty())
                .set("address", enterpriseHistory.getAddress())
                .set("status","0")
                .eq("base_id", enterpriseHistory.getBaseId());

        if(StringUtils.equals("长期",enterpriseHistory.getEnterpriseTermType())){
            updateWrapper.set("enterprise_term_start", null);
            updateWrapper.set("enterprise_term_end", null);
        }
        if(StringUtils.equals("短期",enterpriseHistory.getEnterpriseTermType())){
            updateWrapper.set("enterprise_term_start", enterpriseHistory.getEnterpriseTermStart());
            updateWrapper.set("enterprise_term_end",  enterpriseHistory.getEnterpriseTermEnd());
        }


        luLianEnterpriseHistoryMapper.update(null, updateWrapper);

        //更新营业执照
        LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseHistory.getBaseId());
        if(luLianEnterpriseProve != null){
            luLianEnterpriseProve.setBusinessLicenseUrl(request.getBusinessLicenseUrl());
            luLianEnterpriseProveMapper.updateById(luLianEnterpriseProve);
        }else{
            if(StringUtils.isNotBlank(request.getBusinessLicenseUrl())){
                luLianEnterpriseProve = LuLianEnterpriseProve.builder()
                        .baseId(IdUtil.simpleUUID())
                        .businessLicenseUrl(request.getBusinessLicenseUrl())
                        .build();
                luLianEnterpriseProveMapper.insert(luLianEnterpriseProve);
            }
        }

        //构建复加表数据
        LuLianEnterpriseHistoryCi luLianEnterpriseHistoryCi = luLianEnterpriseHistoryCiMapper.selectOne(new QueryWrapper<LuLianEnterpriseHistoryCi>().eq("pk_id", enterpriseHistory.getBaseId()));
        if(luLianEnterpriseHistoryCi != null){
            String ciId = luLianEnterpriseHistoryCi.getBaseId();
            BeanUtils.copyProperties(request,luLianEnterpriseHistoryCi);
            luLianEnterpriseHistoryCi.setBaseId(ciId);
             luLianEnterpriseHistoryCiMapper.updateCustomById(luLianEnterpriseHistoryCi);
        }else{
            luLianEnterpriseHistoryCi = new LuLianEnterpriseHistoryCi();
            BeanUtils.copyProperties(request,luLianEnterpriseHistoryCi);
            luLianEnterpriseHistoryCi.setBaseId(IdUtil.simpleUUID());
            luLianEnterpriseHistoryCi.setPkId(enterpriseHistory.getBaseId());
            luLianEnterpriseHistoryCiMapper.insertCustomById(luLianEnterpriseHistoryCi);
        }

        //构建行业门类
        List<LuLianEnterpriseMainIndustry> mainIndustrys = request.getMainIndustrys();
        if(mainIndustrys != null && !mainIndustrys.isEmpty()){
            List<LuLianEnterpriseMainIndustry> collect = mainIndustrys.stream().map(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setEnterpriseId(request.getBaseId());
                return item;
            }).collect(Collectors.toList());
            //删除企业原有的行业门类
            luLianEnterpriseMainIndustryMapper.delete(new QueryWrapper<LuLianEnterpriseMainIndustry>().eq("enterprise_id",request.getBaseId()));

            //插入新的行业门类
            luLianEnterpriseMainIndustrySerivce.saveOrUpdateBatch(collect);
        }
        return Message.success();
    }

    @Autowired
    private LuLianEnterpriseMainIndustryMapper luLianEnterpriseMainIndustryMapper;

    /**
     * 数据回显
     *
     * @param userId
     * @return
     */
    @Override
    public Message enterpriseHistoryShow(String userId) {
        if(StringUtils.isBlank(userId)){
            return Message.fail("没有找到创建人Id");
        }
        LuLianEnterpriseRenZhengRequest resp = new LuLianEnterpriseRenZhengRequest();

        //查询用户关联的企业
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserMapper.selectOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));

        if(enterpriseUser == null){
            return Message.success(resp);
        }

        LuLianEnterpriseHistory enterpriseHistory = luLianEnterpriseHistoryMapper.selectOne(new QueryWrapper<LuLianEnterpriseHistory>().eq("base_id",enterpriseUser.getEnterpriseId()));
        if(enterpriseHistory != null){
            resp.setBaseId(enterpriseHistory.getBaseId());
            resp.setBaseName(enterpriseHistory.getBaseName());
            resp.setUnicode(enterpriseHistory.getUnicode());
            resp.setLegalPerson(enterpriseHistory.getLegalPerson());
            resp.setRegisterCapital(enterpriseHistory.getRegisterCapital());
            resp.setEnterpriseTermType(enterpriseHistory.getEnterpriseTermType());
            resp.setProvince(enterpriseHistory.getProvince());
            resp.setRegisterType(enterpriseHistory.getRegisterType());
            resp.setCity(enterpriseHistory.getCity());
            resp.setCounty(enterpriseHistory.getCounty());
            resp.setAddress(enterpriseHistory.getAddress());
            resp.setStatus(enterpriseHistory.getStatus());
            resp.setLinkMan(enterpriseHistory.getLinkMan());
            resp.setLinkPhone(enterpriseHistory.getLinkPhone());
            resp.setEnterpriseTermStart(enterpriseHistory.getEnterpriseTermStart());
            resp.setEnterpriseTermEnd(enterpriseHistory.getEnterpriseTermEnd());
            //取出企业ID
            String enterpriseId = enterpriseHistory.getBaseId();
            //获取复加信息
            LuLianEnterpriseHistoryCi luLianEnterpriseHistoryCi = luLianEnterpriseHistoryCiMapper.selectDataByEnterpriseId(enterpriseId);
            if(luLianEnterpriseHistoryCi != null){
                resp.setActualProvince(luLianEnterpriseHistoryCi.getActualProvince());
                resp.setActualCity(luLianEnterpriseHistoryCi.getActualCity());
                resp.setActualCounty(luLianEnterpriseHistoryCi.getActualCounty());
                resp.setActualAddress(luLianEnterpriseHistoryCi.getActualAddress());
                resp.setBusinessModel(luLianEnterpriseHistoryCi.getBusinessModel());
                resp.setBusinessModelOther(luLianEnterpriseHistoryCi.getBusinessModelOther());
                resp.setAccountPre(luLianEnterpriseHistoryCi.getAccountPre());
                resp.setInvoicingCapability(luLianEnterpriseHistoryCi.getInvoicingCapability());
                resp.setSupplyArea(luLianEnterpriseHistoryCi.getSupplyArea());
                resp.setSupplyCategories(luLianEnterpriseHistoryCi.getSupplyCategories());
                resp.setGetType(luLianEnterpriseHistoryCi.getGetType());
                resp.setGetTypeOther(luLianEnterpriseHistoryCi.getGetTypeOther());
                resp.setGetServices(luLianEnterpriseHistoryCi.getGetServices());
                resp.setGetServicesOther(luLianEnterpriseHistoryCi.getGetServicesOther());
            }
            LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseId);
            if(luLianEnterpriseProve != null){
                resp.setBusinessLicenseUrl(luLianEnterpriseProve.getBusinessLicenseUrl());
            }

            List<LuLianEnterpriseMainIndustry> mainIndustries = luLianEnterpriseMainIndustrySerivce.list(new QueryWrapper<LuLianEnterpriseMainIndustry>().eq("enterprise_id", enterpriseId));
            if(mainIndustries != null && !mainIndustries.isEmpty()){
                resp.setMainIndustrys(mainIndustries);
            }

            //查询检查记录
            if(StringUtils.equals(enterpriseHistory.getStatus(),"2")){
                List<LuLianShowEnterpriseAuth> luLianShowEnterpriseAuths = luLianShowEnterpriseAuthMapper.selectList(new QueryWrapper<LuLianShowEnterpriseAuth>().eq("enterprise_id", enterpriseId).orderByDesc("base_create_time"));
                if(luLianShowEnterpriseAuths != null && !luLianShowEnterpriseAuths.isEmpty()){
                    LuLianShowEnterpriseAuth luLianShowEnterpriseAuth = luLianShowEnterpriseAuths.get(0);
                    resp.setRemarks(luLianShowEnterpriseAuth.getRemark());
                }
            }
        }
        return Message.success(resp);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message enterpriseCheck(Map<String, String> params,String userId) {
        String baseId = params.get("baseId");
        String code = params.get("code");
        String remark = params.get("remark");

        if(StringUtils.equals(code,"1") || StringUtils.equals(code,"2")){
            LuLianEnterpriseHistory enterpriseHistory= LuLianEnterpriseHistory.builder()
                    .baseId(baseId)
                    .status(code)
                    .build();
            luLianEnterpriseHistoryMapper.updateById(enterpriseHistory);
            LuLianShowEnterpriseAuth build = LuLianShowEnterpriseAuth.builder()
                    .userId(userId)
                    .baseId(IdUtil.simpleUUID())
                    .remark(remark)
                    .enterpriseId(baseId)
                    .baseCreateTime(new Date())
                    .baseUpdateTime(new Date())
                    .build();
            luLianShowEnterpriseAuthMapper.insert(build);
        }else{
            return Message.fail("没有找到对应的状态");
        }
        return Message.success();
    }

    @Override
    public List<EnterpriseAuthVo> queryEnterHistoryList(Page page, EnterpriseSelectDto enterpriseSelectDto) {
        List<EnterpriseAuthVo> r = luLianEnterpriseHistoryMapper.queryEnterHistoryList(page,enterpriseSelectDto);
        return r;
    }

    @Override
    public Map<String, String> queryEnterpriseIdAndName(String userId) {
        return luLianEnterpriseHistoryMapper.getEnterpriseIdAndName(userId);
    }

    /**
     * 云展厅企业认证
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message yunZhanTingEnterpriseHistory(YunZhanTingEnterpriseHistoryRequest request,String userId ) {
            //社会统一信用代码
            String unicode = request.getUnicode();
            Integer enterpriseCount = luLianEnterpriseHistoryMapper.selectCount(new QueryWrapper<LuLianEnterpriseHistory>().eq("unicode", unicode));
            if(enterpriseCount > 0){
                return Message.fail(String.format("当前企业【%s】已存在",unicode));
            }else{
                String enterpriseId = StringUtils.isNotBlank(request.getBaseId()) ? request.getBaseId() : IdUtil.simpleUUID();
                LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder()
                        .enterpriseId(enterpriseId)
                        .userId(userId)
                        .baseId(IdUtil.simpleUUID())
                        .build();

                //构建History数据
                LuLianEnterpriseHistory enterpriseHistory = new LuLianEnterpriseHistory();
                BeanUtil.copyProperties(request,enterpriseHistory,"adminRole","mainIndustrys","businessLicenseUrl","authenticationUrl","otherCertificatesUrl","userName");
                enterpriseHistory.setBaseId(enterpriseId);
                enterpriseHistory.setRegisterCapital(request.getRegisterCapital());
                enterpriseHistory.setEnterpriseTermType(request.getEnterpriseTermType());
                enterpriseHistory.setEnterpriseTermStart(request.getEnterpriseTermStart());
                enterpriseHistory.setEnterpriseTermEnd(request.getEnterpriseTermEnd());
                enterpriseHistory.setIsAuth(false);
                enterpriseHistory.setExamineStatus("");
                enterpriseHistory.setStatus("1");
                enterpriseHistory.setCreator(userId);
                enterpriseHistory.setContactAddress(request.getContactAddress());
                enterpriseHistory.setBaseCreateTime(DateUtil.formatDateTime(new Date()));

                //如果不是Null当前就是管理员在新增数据
                if(StringUtils.isNotBlank(request.getAdminRole())){
                    if(StringUtils.isBlank(request.getUserPhone())){
                        return Message.fail("请输入企业用户名");
                    }
                    Message userIdMap = cloudShowManagerSubService.getUserIdByUserName(request.getUserPhone());
                    if(Objects.isNull(userIdMap.getObj())){
                        return Message.fail("没有找到该用户：" + request.getUserPhone());
                    }
                    Map<String,String> obj = (Map<String,String>)userIdMap.getObj();
                    String remoteUserId = obj.get("userId");
                    if(StringUtils.isBlank(remoteUserId)){
                        return Message.fail("没有找到该用户：" + request.getUserPhone());
                    }

                    //复写userId,上面的userId是当前管理员的userId，这里要改成真实用户的userID
                    enterpriseUser.setUserId(remoteUserId);
                    enterpriseHistory.setStatus("1");

                    List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", remoteUserId));
                    if(enterpriseUserList != null && !enterpriseUserList.isEmpty()){
                        return Message.fail("当前账号：【" + request.getUserPhone() + "】已绑定企业" );
                    }

                    //管理员新增往show_enterprise表中存一份数据
                    LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
                    int luLianEnterpriseCount = luLianEnterpriseService.count(new QueryWrapper<LuLianEnterprise>().eq("unicode", enterpriseHistory.getUnicode()));
                    if(luLianEnterpriseCount > 0 ){
                        return Message.fail("当前企业在上线表中已存在【"+enterpriseHistory.getUnicode()+"】，需要核实");
                    }
                    BeanUtil.copyProperties(enterpriseHistory,luLianEnterprise);
                    luLianEnterpriseService.saveOrUpdate(luLianEnterprise);
                    //新增用户的认证企业的角色
//                    Map<String, String> params = new HashMap<>(16);
//                    params.put("userId", remoteUserId);
//                    params.put("roleId", "043ea2e3e02c4aa591df1f83e65069bc");
//                    Message me = cloudShowManagerSubService.addUserRole(params);
//                    if(me.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
//                        throw new RuntimeException("保存用户角色失败");
//                    }
                }else{
                    //非管理员查询当前账号是否绑定过企业
                    List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
                    if(enterpriseUserList != null && enterpriseUserList.size() > 0){
                        return Message.fail("当前用户已绑定企业" );
                    }
                    Map<String, String> params = new HashMap<>(16);
                    params.put("userId", userId);
                    params.put("roleId", "043ea2e3e02c4aa591df1f83e65069bc");
                    Message me = cloudShowManagerSubService.addUserRole(params);
                    if(me.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("保存用户角色失败");
                    }
                }
                luLianEnterpriseUserMapper.insert(enterpriseUser);
                luLianEnterpriseHistoryMapper.insert(enterpriseHistory);
                //添加进VR审核库
                 EnterpriseVr enterpriseVr=new EnterpriseVr();
                 enterpriseVr.setBaseId(IdUtil.simpleUUID());
                 enterpriseVr.setEnterpriseId(enterpriseId);
                 enterpriseVr.setBelongTo(userId);
                 enterpriseVr.setBaseCreateTime(DateUtil.formatDateTime(new Date()));
                 enterpriseVrMapper.insert(enterpriseVr);

                //插入营业执照数据
                LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseId);
                if(luLianEnterpriseProve != null){
                    luLianEnterpriseProve.setBusinessLicenseUrl(request.getBusinessLicenseUrl());
                    luLianEnterpriseProveMapper.updateById(luLianEnterpriseProve);
                }else{
                    if(StringUtils.isNotBlank(request.getBusinessLicenseUrl())){
                        luLianEnterpriseProve = LuLianEnterpriseProve.builder()
                                .baseId(IdUtil.simpleUUID())
                                .enterpriseId(enterpriseId)
                                .businessLicenseUrl(request.getBusinessLicenseUrl())
                                .build();
                        luLianEnterpriseProveMapper.insert(luLianEnterpriseProve);
                    }
                }

                //构建行业门类
                List<LuLianEnterpriseMainIndustry> mainIndustrys = request.getMainIndustrys();
                if(mainIndustrys != null && !mainIndustrys.isEmpty()){
                    List<LuLianEnterpriseMainIndustry> collect = mainIndustrys.stream().map(item -> {
                        item.setEnterpriseId(enterpriseId);
                        return item;
                    }).collect(Collectors.toList());
                    luLianEnterpriseMainIndustrySerivce.saveOrUpdateBatch(collect);
                }

                //保存数据到Search表中
                //查询行政区
                SysArea sysArea = null;
                if(StringUtils.isNotBlank(enterpriseHistory.getCity())){
                    sysArea = sysAreaMapper.selectById(enterpriseHistory.getCity());
                }
                SysDictData sysDictData = null;

                if(mainIndustrys != null && mainIndustrys.size() > 0){
                    LuLianEnterpriseMainIndustry luLianEnterpriseMainIndustry = mainIndustrys.get(0);
                    if(luLianEnterpriseMainIndustry != null && StringUtils.isNotBlank(luLianEnterpriseMainIndustry.getFristDictId())){
                        sysDictData = sysDictDataMapper.selectById(luLianEnterpriseMainIndustry.getFristDictId());
                    }
                }

                SearchDto searchDto = SearchDto.builder()
                        .baseName(enterpriseHistory.getBaseName())
                        .unicode(enterpriseHistory.getUnicode())
                        .registerTime(enterpriseHistory.getRegisterTime() != null ? DateUtil.format(enterpriseHistory.getRegisterTime(), "yyyy/MM/dd") : null)
                        .address(enterpriseHistory.getAddress())
                        .businessScope(enterpriseHistory.getBusinessScope())
                        .baseIntroduction(enterpriseHistory.getBaseIntroduction())
                        .logo(enterpriseHistory.getLogo())
                        .isScale("0")
                        .isLead(enterpriseHistory.getIsLead())
                        .isGazelle(enterpriseHistory.getIsGazelle())
                        .isChampion(enterpriseHistory.getIsChampion())
                        .isSpecial(enterpriseHistory.getIsSpecial())
                        .isGiant(enterpriseHistory.getIsGiant())
                        .isUnicorn(enterpriseHistory.getIsUnicorn())
                        .isHightech(enterpriseHistory.getIsHightech())
                        .registerCapital(enterpriseHistory.getRegisterCapital() == 0.0 ? null : String.valueOf(enterpriseHistory.getRegisterCapital()))
                        .build();
                if(sysArea != null && StringUtils.isNotBlank(sysArea.getBaseName())){
                    searchDto.setCity(sysArea.getBaseName());
                }

                if(sysDictData != null && StringUtils.isNotBlank(sysDictData.getBaseName())){
                    searchDto.setIndustry(sysDictData.getBaseName());
                }

                Message message = scaleEnterpriseService.addEnterprise(searchDto);
                if(message.getCode() == 1){
                    throw new RuntimeException("写入搜索库失败");
                }
            }

            if(StringUtils.isBlank(request.getAdminRole())){
                notificationUtils.saveAndSendMessage(userId,"3d611d48853f11ea9e870221860e9b7e","企业：" + request.getBaseName() + "已提交企业认证，请审核");
            }
            return Message.success("保存成功");
    }

    @Override
    public Message yunZhanTingEnterpriseHistoryShow(String userId) {
        if(StringUtils.isBlank(userId)){
            return Message.fail("没有找到创建人Id");
        }
        YunZhanTingEnterpriseHistoryRequest resp = new YunZhanTingEnterpriseHistoryRequest();
        //查询用户关联的企业
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserMapper.selectOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            return Message.success(resp);
        }
        LuLianEnterpriseHistory enterpriseHistory = luLianEnterpriseHistoryMapper.selectOne(new QueryWrapper<LuLianEnterpriseHistory>().eq("base_id",enterpriseUser.getEnterpriseId()));
        if(enterpriseHistory != null){
            resp.setBaseId(enterpriseHistory.getBaseId());
            resp.setBaseName(enterpriseHistory.getBaseName());
            resp.setUnicode(enterpriseHistory.getUnicode());
            resp.setLegalPerson(enterpriseHistory.getLegalPerson());
            resp.setRegisterCapital(enterpriseHistory.getRegisterCapital());
            resp.setProvince(enterpriseHistory.getProvince());
            resp.setRegisterType(enterpriseHistory.getRegisterType());
            resp.setCity(enterpriseHistory.getCity());
            resp.setCounty(enterpriseHistory.getCounty());
            resp.setAddress(enterpriseHistory.getAddress());
            resp.setStatus(enterpriseHistory.getStatus());
            resp.setBusinessScope(enterpriseHistory.getBusinessScope());
            resp.setLinkMan(enterpriseHistory.getLinkMan());
            resp.setRegisterTime(enterpriseHistory.getRegisterTime());
            resp.setLinkPhone(enterpriseHistory.getLinkPhone());
            resp.setEnterpriseTermType(enterpriseHistory.getEnterpriseTermType());
            resp.setEnterpriseTermStart(enterpriseHistory.getEnterpriseTermStart());
            resp.setEnterpriseTermEnd(enterpriseHistory.getEnterpriseTermEnd());
            resp.setWebSite(enterpriseHistory.getWebSite());
//            resp.setTradeFirst(enterpriseHistory.getTradeFirst());
//            resp.setTradeSecond(enterpriseHistory.getTradeSecond());
            resp.setFixedPhone(enterpriseHistory.getFixedPhone());
            resp.setEmail(enterpriseHistory.getEmail());
            resp.setContactAddress(enterpriseHistory.getContactAddress());
            resp.setScale(enterpriseHistory.getScale());
            resp.setAnnualTurnover(enterpriseHistory.getAnnualTurnover());
            resp.setRemark(enterpriseHistory.getRemarks());

            //取出企业ID
            String enterpriseId = enterpriseHistory.getBaseId();
            //查询上传的文件
            LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseId);
            if(luLianEnterpriseProve != null){
                resp.setBusinessLicenseUrl(luLianEnterpriseProve.getBusinessLicenseUrl());
                resp.setOtherCertificatesUrl(luLianEnterpriseProve.getOtherCertificatesUrl());
                resp.setAuthenticationUrl(luLianEnterpriseProve.getAuthenticationUrl());
            }

            //查询行业
            List<LuLianEnterpriseMainIndustry> mainIndustries = luLianEnterpriseMainIndustrySerivce.list(new QueryWrapper<LuLianEnterpriseMainIndustry>().eq("enterprise_id", enterpriseId));
            if(mainIndustries != null && !mainIndustries.isEmpty()){
                resp.setMainIndustrys(mainIndustries);
            }
        }
        return Message.success(resp);
    }

    /**
     * 修改
     *
     * @param request
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message yunZhanTingUpdateEnterpriseHistory(YunZhanTingEnterpriseHistoryRequest request, String userId) {
        if(StringUtils.isBlank(request.getBaseId())){
            return Message.fail("没有找到BaseId");
        }

        LuLianEnterpriseHistory enterpriseHistory = luLianEnterpriseHistoryMapper.selectById(request.getBaseId());
        BeanUtils.copyProperties(request,enterpriseHistory);
        enterpriseHistory.setExamineStatus("");
        enterpriseHistory.setStatus("0");
        enterpriseHistory.setBaseUpdateTime(DateUtil.formatDateTime(new Date()));

        UpdateWrapper<LuLianEnterpriseHistory> updateWrapper = new UpdateWrapper<LuLianEnterpriseHistory>()
                .set("base_name", enterpriseHistory.getBaseName())
                .set("unicode", enterpriseHistory.getUnicode())
                .set("legal_person", enterpriseHistory.getLegalPerson())
                .set("register_type", enterpriseHistory.getRegisterType())
                .set("business_nature",enterpriseHistory.getBusinessNature())
                .set("register_time",enterpriseHistory.getRegisterTime())
                .set("web_site",enterpriseHistory.getWebSite())
                .set("link_man",enterpriseHistory.getLinkMan())
                .set("link_phone",enterpriseHistory.getLinkPhone())
                .set("fixed_phone",enterpriseHistory.getFixedPhone())
                .set("email",enterpriseHistory.getEmail())
                .set("contact_address",enterpriseHistory.getContactAddress())
                .set("scale",enterpriseHistory.getScale())
//                .set("trade_first",enterpriseHistory.getTradeFirst())
                .set("annual_turnover",enterpriseHistory.getAnnualTurnover())
//                .set("trade_second",enterpriseHistory.getTradeSecond())
                .set("register_capital", enterpriseHistory.getRegisterCapital())
                .set("enterprise_term_type", enterpriseHistory.getEnterpriseTermType())
                .set("province", enterpriseHistory.getProvince())
                .set("business_scope", enterpriseHistory.getBusinessScope())
                .set("city", enterpriseHistory.getCity())
                .set("county", enterpriseHistory.getCounty())
                .set("address", enterpriseHistory.getAddress())
                .set("status","0")
                .eq("base_id", enterpriseHistory.getBaseId());

        if(StringUtils.equals("长期",enterpriseHistory.getEnterpriseTermType())){
            updateWrapper.set("enterprise_term_start", null);
            updateWrapper.set("enterprise_term_end", null);
        }
        if(StringUtils.equals("短期",enterpriseHistory.getEnterpriseTermType())){
            updateWrapper.set("enterprise_term_start", enterpriseHistory.getEnterpriseTermStart());
            updateWrapper.set("enterprise_term_end",  enterpriseHistory.getEnterpriseTermEnd());
        }
        luLianEnterpriseHistoryMapper.update(null, updateWrapper);
        //更新营业执照
        LuLianEnterpriseProve luLianEnterpriseProve = luLianEnterpriseProveMapper.selectEnterpriseId(enterpriseHistory.getBaseId());
        if(luLianEnterpriseProve != null){
            luLianEnterpriseProve.setBusinessLicenseUrl(request.getBusinessLicenseUrl());
            luLianEnterpriseProve.setAuthenticationUrl(request.getAuthenticationUrl());
            luLianEnterpriseProve.setOtherCertificatesUrl(request.getOtherCertificatesUrl());
            luLianEnterpriseProveMapper.updateById(luLianEnterpriseProve);
        }else{
            if(StringUtils.isNotBlank(request.getBusinessLicenseUrl())){
                luLianEnterpriseProve = LuLianEnterpriseProve.builder()
                        .baseId(IdUtil.simpleUUID())
                        .businessLicenseUrl(request.getBusinessLicenseUrl())
                        .authenticationUrl(request.getAuthenticationUrl())
                        .otherCertificatesUrl(request.getOtherCertificatesUrl())
                        .build();
                luLianEnterpriseProveMapper.insert(luLianEnterpriseProve);
            }
        }
        //构建行业门类
        List<LuLianEnterpriseMainIndustry> mainIndustrys = request.getMainIndustrys();
        if(mainIndustrys != null && !mainIndustrys.isEmpty()){
            List<LuLianEnterpriseMainIndustry> collect = mainIndustrys.stream().map(item -> {
                item.setBaseId(IdUtil.simpleUUID());
                item.setEnterpriseId(request.getBaseId());
                return item;
            }).collect(Collectors.toList());
            //删除企业原有的行业门类
            luLianEnterpriseMainIndustryMapper.delete(new QueryWrapper<LuLianEnterpriseMainIndustry>().eq("enterprise_id",request.getBaseId()));

            //插入新的行业门类
            luLianEnterpriseMainIndustrySerivce.saveOrUpdateBatch(collect);
        }

        //保存数据到Search表中
        //查询行政区
        SysArea sysArea = null;
        if(StringUtils.isNotBlank(enterpriseHistory.getCity())){
            sysArea = sysAreaMapper.selectById(enterpriseHistory.getCity());
        }
        SysDictData sysDictData = null;
        if(mainIndustrys != null && mainIndustrys.size() > 0){
            LuLianEnterpriseMainIndustry luLianEnterpriseMainIndustry = mainIndustrys.get(0);
            if(luLianEnterpriseMainIndustry != null && StringUtils.isNotBlank(luLianEnterpriseMainIndustry.getFristDictId())){
                sysDictData = sysDictDataMapper.selectById(luLianEnterpriseMainIndustry.getFristDictId());
            }
        }
        SearchDto searchDto = SearchDto.builder()
                .baseName(enterpriseHistory.getBaseName())
                .unicode(enterpriseHistory.getUnicode())
                .registerTime(enterpriseHistory.getRegisterTime() != null ? DateUtil.format(enterpriseHistory.getRegisterTime(), "yyyy/MM/dd") : null)
                .address(enterpriseHistory.getAddress())
                .businessScope(enterpriseHistory.getBusinessScope())
                .baseIntroduction(enterpriseHistory.getBaseIntroduction())
                .logo(enterpriseHistory.getLogo())
                .isLead(enterpriseHistory.getIsLead())
                .isGazelle(enterpriseHistory.getIsGazelle())
                .isChampion(enterpriseHistory.getIsChampion())
                .isSpecial(enterpriseHistory.getIsSpecial())
                .isGiant(enterpriseHistory.getIsGiant())
                .isUnicorn(enterpriseHistory.getIsUnicorn())
                .isHightech(enterpriseHistory.getIsHightech())
                .registerCapital(enterpriseHistory.getRegisterCapital() == 0.0 ? null : String.valueOf(enterpriseHistory.getRegisterCapital()))
                .build();
        if(sysArea != null && StringUtils.isNotBlank(sysArea.getBaseName())){
            searchDto.setCity(sysArea.getBaseName());
        }
        if(sysDictData != null && StringUtils.isNotBlank(sysDictData.getBaseName())){
            searchDto.setIndustry(sysDictData.getBaseName());
        }

        Message message = scaleEnterpriseService.addEnterprise(searchDto);
        if(message.getCode() == 1){
            throw new RuntimeException("写入搜索库失败");
        }
        return Message.success();
    }
}